package com.seaboxdata.jt809.kafka;

import com.seaboxdata.jt809.common.util.PropertiesUtil;
import com.seaboxdata.jt809.db.JT809Dao;
import com.seaboxdata.jt809.kafka.serializer.JT809Packet0x1202Deserializer;
import com.seaboxdata.jt809.packet.JT809Packet0x1402;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName JT809Packet0x1402MessageConsumer
 * @Description TODO
 * @Author DFJX
 * @Company 北京东方金信科技有限公司
 * @Date 2020/7/21 13:59
 * Version 1.0
 **/
public class JT809Packet0x1402MessageConsumer {
    public void getMessage(){
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, PropertiesUtil.getProperty("kafka.server"));
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "warn-group");
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JT809Packet0x1202Deserializer.class.getName());
        KafkaConsumer<String, JT809Packet0x1402> consumer = new KafkaConsumer<String, JT809Packet0x1402>(props);
        consumer.subscribe(Collections.singletonList("warn"));
        List<JT809Packet0x1402> list=new ArrayList<JT809Packet0x1402>();
        long batchSize=Long.valueOf(PropertiesUtil.getProperty("batch.size"))==0?10000:Long.valueOf(PropertiesUtil.getProperty("batch.size"));
        long interval=Long.valueOf(PropertiesUtil.getProperty("interval"))==0?10:Long.valueOf(PropertiesUtil.getProperty("interval"));
        long begin=System.currentTimeMillis();
        while (true){
            ConsumerRecords<String, JT809Packet0x1402> messages = consumer.poll(100L);
            for (ConsumerRecord<String, JT809Packet0x1402> message : messages) {
                list.add(message.value());
                //System.out.println("kafka读取到数据。。。。。。");
                long end=System.currentTimeMillis();
                if((end-begin)/1000>=interval){
                    JT809Dao.batchAdd0x1402(list);
                    list=new ArrayList<JT809Packet0x1402>();
                    begin=System.currentTimeMillis();
                }

            }
        }

    }
}
